package 事务操作;

import java.sql.*;
import java.util.Scanner;

public class test03 {    public static void main(String[] args) {
    String fkf = null;
    String skf = null;
    int rmb = 0;
    //接收用户输入 scanner
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入本次转账金额：");
    rmb = sc.nextInt();
    System.out.println("请输入付款方id：");
    fkf = sc.next();
    System.out.println("请输入收款方id：");
    skf = sc.next();
    System.out.println("正在转账"+rmb+"元");
    String url = "jdbc:mysql://localhost/db_jdbc_demo?jdbc:mysql://IP地址:3306/数据库名称?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
    String user = "root";
    String pass = "200233";
    Connection conn= null;
    PreparedStatement pstmt = null;
    //将Statment换成高级版

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(url,user,pass);
        String sql1 = "update t_account set money = money - ? where id = ?";
        String sql2 = "update t_account set money = money + ? where id = ?";
        //开启事务
        conn.setAutoCommit(false);
        pstmt = conn.prepareStatement(sql1);
        //将？换成数值
        pstmt.setInt(1,rmb);
        pstmt.setString(2,fkf);
        int i= pstmt.executeUpdate();
        pstmt = conn.prepareStatement(sql2);
        //将？换成数值
        pstmt.setInt(1,rmb);
        pstmt.setString(2,skf);
        int j= pstmt.executeUpdate();

        if (i+j==2){
            System.out.println("转账成功");
            conn.commit();
        }else {
            System.out.println("转账失败");
        }
    }catch (Exception e){
        e.printStackTrace();
        System.out.println("转账出现错误");
        try {
            conn.rollback();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }finally {
        try {
            pstmt.close();
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
}
